<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

final class Produkter extends BIT_Model
{
	public static $class_name = __CLASS__;
	
	protected $id;
	
	protected $typ;
	
	protected $namn;
	
	protected $beskrivning;
	
	protected $pris;
	
	protected $paket;
	
	protected $erjudande;
	
	protected $pos;
	
	protected $recept;
	
	protected $art;
	
	protected $fangst;

	protected $hallbarhet;
	
	protected $produktionsmetod;

	protected $bildurl;
	
	private $db = "";
	
	function __construct(){
		parent::__construct();
	}
	
	public function getProductPageProducts(){
		$db = get_instance()->db;

		$products = $db->where('typ !=', 'mix')->order_by('pos' ,'asc')->get('produkter')->result();
		$packages = $db->where('typ', 'mix')->order_by('pos' ,'asc')->get('produkter')->result();
		
		$products = $this->mergeProdsAndPackagesNicely( $products, $packages, 3 /* boxes in width */ );

		return $products;
	}

	public function getStartpageProducts( $limit = 6 ){
		$db = get_instance()->db;

		// select two products and one package, merge them (package last) and return
		$products = $db->where('typ !=', 'mix')->order_by('pos' ,'asc')->get('produkter')->result();
		$packages = $db->where('typ', 'mix')->order_by('pos' ,'asc')->get('produkter')->result();

		// Sort in packages nicely
		$products = $this->mergeProdsAndPackagesNicely( $products, $packages, 2 /*width*/);
		
		return array_splice($products, 0, $limit);
	}

	private function mergeProdsAndPackagesNicely( $products = array(), $packages = array(), $boxwidthcount = 3){
		$packageRow = true;
		$pos = 0;

		for($i = 0; $i<count($packages);$i++ ){

			$p = $packages[$i];

			if( $packageRow	) {
				$pos += $boxwidthcount;
				$packageRow = false;
			}
			else {
				$pos += ( $boxwidthcount > 2? $boxwidthcount-1 : $boxwidthcount );
				$packageRow = true;
			}
			// put the package in the array
			array_splice($products, $pos, 1, array($p));
			$pos += 1;
		}

		return $products;
	}

	public function getProduct( $id ){
		$db = get_instance()->db;
		$prod = $db->where('id',$id)->limit(1)->get('produkter')->result();
		return $prod[0];
	}

	public function getBestSellers( $limit = 3 ){
		$db = get_instance()->db;
		return $db->limit( $limit )->order_by('pos')->get('produkter')->result();
	}

	public function getProducts() {
		return $db->get('produkter')->result();
	}
		
	public function saveProduct($data){
		
		if(!$data){
			return false;
		}

		foreach($data as $key => $value){
			$this->$key = $value;
		}
		
		$this->save();
		
		return true;
	}
}